package com.beyondsoft.mcms.web;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.beyondsoft.mcms.common.CommonUtils;
import com.beyondsoft.mcms.common.Constants;
import com.beyondsoft.mcms.common.UmsApiServiceImpl;
import com.beyondsoft.mcms.domain.Advice;
import com.beyondsoft.mcms.domain.Category;
import com.beyondsoft.mcms.domain.Conference;
import com.beyondsoft.mcms.domain.GroupInfo;
import com.beyondsoft.mcms.domain.Item;
import com.beyondsoft.mcms.domain.MemberInfo;
import com.beyondsoft.mcms.service.MemberInfoServiceImpl;

@RequestMapping("/msgsend/**")
@Controller
public class MsgSendController {
	@Autowired
	JavaMailSenderImpl mailSender;
	@Autowired
	SimpleMailMessage mailMessage;

	public static String getFullPath(HttpServletRequest request) throws Exception{
		/*
		String ipAddr = InetAddress.getLocalHost().getHostAddress();
        int port = request.getLocalPort();
        */
		
		String contextPath = request.getContextPath();
        String fullPath = CommonUtils.getRequestAddr(request) + contextPath + "/conferences/" ;
		return fullPath;
	}
	
    //@RequestMapping(method = RequestMethod.POST, value = "{id}")
    //public void post(@PathVariable Long id, ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) {
    //}

    @RequestMapping
    public String index(Model uiModel) {
    	
    	List<Conference> conferences = Conference.findConferencesByNameLikeAndConferenceTypeAndConferenceStatus(
    					null, null, Item.findItem(Constants.CONFERENCE_STATUS_NOADVICING)).getResultList();
    	uiModel.addAttribute("conferences", conferences);
    	if (conferences == null || conferences.size() == 0) {
    		List<String[]> dependencies = new ArrayList<String[]>();
            dependencies.add(new String[] { "conferences", "conferences" });
            uiModel.addAttribute("dependencies", dependencies);
        }
                
    	List<GroupInfo> groupinfoes = GroupInfo.findAllGroupInfoes();
    	uiModel.addAttribute("groupinfoes", groupinfoes);
    	
        return "msgsend/index";
    }
    
    @RequestMapping(value="sendadvice")
    public String sendadvice(@RequestParam("conference") Conference conference,
    		@RequestParam("groupinfo") GroupInfo groupinfo, HttpServletRequest request) {
    	
    	String[] members = request.getParameterValues("members");
    	List<MemberInfo> memberinfoList = new ArrayList<MemberInfo>();
    	for (int i=0; i<members.length; i++){
    		MemberInfo member = MemberInfo.findMemberInfo(Long.valueOf(members[i]));
    		memberinfoList.add(member);
    	}
    	
    	if (memberinfoList.size() == 0){
    		return "redirect:/advices/" ;
    		
    	}
    	
    	new MemberInfoServiceImpl().generateConferenceAdvices(conference, memberinfoList);
    	
    	return "redirect:/advices/" ;
    }
    
    @RequestMapping(value="setmessage", params="form")
	public String setMessage(Model uiModel, HttpServletRequest request) {
    	String sendResult = request.getParameter("form");
    	String reason = request.getParameter("reason");
    	
    	if (sendResult!=null && sendResult.equals("emailSuccess")){
    		uiModel.addAttribute("dialogMessage", "邮件发送成功");
    		uiModel.addAttribute("sendType", Constants.MESSAGE_TYPE_MAIL);
    	}else if (sendResult!=null && sendResult.equals("emailFailure")){
    		uiModel.addAttribute("dialogMessage", "邮件发送异常，原因：" + reason);
    		uiModel.addAttribute("sendType", Constants.MESSAGE_TYPE_MAIL);
    	}else if (sendResult!=null && sendResult.equals("smsSuccess")){
    		uiModel.addAttribute("dialogMessage", "短信发送成功");
    		uiModel.addAttribute("sendType", Constants.MESSAGE_TYPE_SMS);
    	}else if (sendResult!=null && sendResult.equals("smsFailure")){
    		uiModel.addAttribute("dialogMessage", "短信发送异常，原因：" + reason);
    		uiModel.addAttribute("sendType", Constants.MESSAGE_TYPE_SMS);
    	}
    	
        List<Conference> conferences = Advice.findConferencesByMemberInfoAndConferenceStatus(null, null).getResultList();
        uiModel.addAttribute("conferences", CommonUtils.convertToNoRepeatedList(conferences));

		List<Item> sendtypes = Item.findItemsByCategoryAndIsValid(Category.findCategory(Constants.MESSAGE_TYPE), true).getResultList();
		uiModel.addAttribute("sendtypes", sendtypes);
//		
//		String contentTemplate = "<div><br/>各会员单位：<br/>" +
//				"现举办XXX活动<br/><br/>" +
//				"此致<br/>" +
//				"深圳市金融信息服务协会<br/>" +
//				"电话：0755-82427325、0755-82265770<br/>" +
//				"地址：中国深圳市银湖路金湖一街CDI大厦  邮编：518029<br/></div>";
//		uiModel.addAttribute("contentTemplate", contentTemplate);
		
		return "msgsend/setmessage";
	}
    
    @RequestMapping(value="sendmessage", params={"ceveiverType","conference", "sendType", "content"})
    public String sendmessage(Conference conference, Long sendType, String content, String ceveiverType,String copyTo,Model uiModel, HttpServletRequest request){
    	
    	List<Advice> advices = Advice.findAdvicesByConferenceAndMemberInfo(conference, null).getResultList();
		
		if (sendType == Constants.MESSAGE_TYPE_MAIL) {			
//			ApplicationContext ctx = ApplicationContextUtils.getApplicationContext();
//			JavaMailSenderImpl mailSender = (JavaMailSenderImpl) ctx.getBean("mailSender");
//			SimpleMailMessage mailMessage = (SimpleMailMessage) ctx.getBean("templateMessage");

			List<String> mailTo = new ArrayList<String>();
			for (Iterator<Advice> it = advices.iterator(); it.hasNext();) {
				Advice advice = (Advice) it.next();
				MemberInfo memberInfo = advice.getMemberInfo();
				String delegateEmail = memberInfo.getDelegateEmail();
				String contactEmail = memberInfo.getContactEmail();
				if("0".equals(ceveiverType)){
					mailTo.add(delegateEmail);
					if (contactEmail!=null && contactEmail.length()>0){
						mailTo.add(contactEmail);
					}
				}else if("1".equals(ceveiverType)){
					mailTo.add(delegateEmail);
				}else{
					if (contactEmail!=null && contactEmail.length()>0){
						mailTo.add(contactEmail);
					}
				}
			}
			
			String[] to = new String[mailTo.size()];

			try {
				MimeMessage mimeMessage = mailSender.createMimeMessage();
				MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "utf-8");
				
				messageHelper.setFrom(mailMessage.getFrom());
				messageHelper.setTo(mailTo.toArray(to));
				
				//抄送
				if(StringUtils.isNotEmpty(copyTo)){
					String[] copytoes=copyTo.split(";");
					messageHelper.setBcc(copytoes);
				}
				
				messageHelper.setSubject("活动通知--" + conference.getName());
				content += "<br/><br/>活动详情请点击下面的链接：<br/><a href='" +getFullPath(request)+conference.getId() + "'>活动简讯</a><br/>";
				messageHelper.setText(content, true);
				mailSender.send(mimeMessage);
				
			} catch (Exception me) {
				System.out.println(me.getMessage());
				return "redirect:/msgsend/setmessage?form=emailFailure&reason=" + me.getLocalizedMessage();
			}
			
			return "redirect:/msgsend/setmessage?form=emailSuccess";
			
		}else if (Long.valueOf(sendType) == Constants.MESSAGE_TYPE_SMS){
			
			
			try{
				
				for (Iterator<Advice> it = advices.iterator(); it.hasNext();) {
					Advice advice = (Advice) it.next();
					MemberInfo memberInfo = advice.getMemberInfo();
					
					String sms = memberInfo.getMemberName() + "（单位），" + removeHtmlTag(content);
					
					String delegateMobile = memberInfo.getDelegateMobile();
					String contactMobile = memberInfo.getContactMobile();
					
					
					if("0".equals(ceveiverType)){
						if (contactMobile!=null && contactMobile.length()==11){
							UmsApiServiceImpl.sendShortMsgByPost(sms, (delegateMobile + "," + contactMobile) );
						}else{
							UmsApiServiceImpl.sendShortMsgByPost(sms, delegateMobile);
						}
						
					}else if("1".equals(ceveiverType)){
						UmsApiServiceImpl.sendShortMsgByPost(sms, delegateMobile);
					}else{
						if (contactMobile!=null && contactMobile.length()==11){
							UmsApiServiceImpl.sendShortMsgByPost(sms, contactMobile);
						}
					}
				}
				
			}catch(Exception e){
				System.out.println(e.getMessage());
				return "redirect:/msgsend/setmessage?form=smsFailure&reason=" + e.getLocalizedMessage();
			}
			return "redirect:/msgsend/setmessage?form=smsSuccess";
		}

		else{
			
			return "redirect:/msgsend/setmessage?form=微信发送还未实现";
		}
		
	}
    
    private String removeHtmlTag(String htmlStr){
    	String resultStr = htmlStr;
    	String regex = "<([^>]*)>";
    	Pattern p = Pattern.compile(regex);
    	Matcher m = p.matcher(htmlStr);
    	while (m.find()){
    		String oldStr = htmlStr.substring(m.start(), m.end());
    		resultStr = resultStr.replace(oldStr, "");
    	}
    	
    	System.out.println(resultStr);
    	return resultStr;
    }
    
}
